﻿function initializeGallery(authorID, albumSwitcher) {
	readAlbums(authorID, function (albums) {
		var $albumsMenu = $("li#albums > ul");

		albums = $.grep(albums, function (i) {
			return 0 == i.title.indexOf(spinnerAlbumPrefix + ":");
		});

		albums = $.map(albums, function (i) {
			return {
				id: i.id,
				title: i.title.substr(spinnerAlbumPrefix.length + 1)
			};
		});

		$.each(albums, function () {
			var album = this;

			function sortByText($list) {
				var items = $list
					.children("li")
					.detach()
					.toArray();

				items.sort(function (lhs, rhs) { return $(lhs).text() < $(rhs).text() ? -1 : $(lhs).text() > $(rhs).text() ? 1 : 0; });
				$list.append($(items));
			}

			readAlbumPhotos(Math.max(screen.width, screen.height), authorID, album.id, function (photos) {
				var $subMenuItem = $("<li><a href='#'>#</a></li>");
				var $subMenuLink = $subMenuItem.children("a").first();

				$subMenuLink.text(album.title);
				$subMenuLink.click(function () {
					albumSwitcher(photos);
				});
				$albumsMenu.append($subMenuItem);
				sortByText($albumsMenu);
			});
		});
	});
}
